var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const axios = require('axios');
const { Store } = require('../model/model');
const Order = require('../model/uni');

const Schedule = require('../model/Schedule');
const Technician = require('../model/Technician');
const User = require('../model/model').User;
const Role = require('../model/model').Role;


// 获取门店列表（支持搜索和分页）
router.get('/stores', async (req, res) => {
    try {
        const {
            page = 1,
            limit = 10,
            search = '',
            status = ''
        } = req.query;

        // 构建查询条件
        const query = {};

        // 搜索条件
        if (search) {
            query.$or = [
                { name: { $regex: search, $options: 'i' } },
                { address: { $regex: search, $options: 'i' } },
                { manager: { $regex: search, $options: 'i' } },
                { phone: { $regex: search, $options: 'i' } }
            ];
        }

        // 状态筛选
        if (status) {
            query.status = status;
        }

        // 计算分页
        const skip = (parseInt(page) - 1) * parseInt(limit);

        // 查询数据
        const stores = await Store.find(query)
            .sort({ createTime: -1 })
            .skip(skip)
            .limit(parseInt(limit));

        // 查询总数
        const total = await Store.countDocuments(query);

        // 计算总页数
        const totalPages = Math.ceil(total / parseInt(limit));

        res.json({
            code: 200,
            message: '获取门店列表成功',
            data: {
                stores,
                pagination: {
                    current: parseInt(page),
                    pageSize: parseInt(limit),
                    total,
                    totalPages
                }
            }
        });
    } catch (error) {
        console.error('获取门店列表失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取门店列表失败',
            error: error.message
        });
    }
});

// 获取门店详情
router.get('/stores/:id', async (req, res) => {
    try {
        const { id } = req.params;

        const store = await Store.findById(id);
        if (!store) {
            return res.status(404).json({
                code: 404,
                message: '门店不存在'
            });
        }

        res.json({
            code: 200,
            message: '获取门店详情成功',
            data: store
        });
    } catch (error) {
        console.error('获取门店详情失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取门店详情失败',
            error: error.message
        });
    }
});


// 获取门店统计信息
router.get('/stores/stats', async (req, res) => {
    try {
        const total = await Store.countDocuments();

        // 按状态统计
        const statusStats = await Store.aggregate([
            {
                $group: {
                    _id: '$status',
                    count: { $sum: 1 }
                }
            }
        ]);

        // 员工总数
        const totalStaff = await Store.aggregate([
            {
                $group: {
                    _id: null,
                    total: { $sum: '$staffCount' }
                }
            }
        ]);

        // 平均员工数
        const averageStaff = total > 0 ? Math.round(totalStaff[0]?.total / total) : 0;

        res.json({
            code: 200,
            message: '获取统计信息成功',
            data: {
                total,
                statusStats: statusStats.reduce((acc, item) => {
                    acc[item._id] = item.count;
                    return acc;
                }, {}),
                totalStaff: totalStaff[0]?.total || 0,
                averageStaff
            }
        });
    } catch (error) {
        console.error('获取统计信息失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取统计信息失败',
            error: error.message
        });
    }
});

// 添加订单
router.post('/orders', async (req, res) => {
    try {
        const orderData = req.body;
        // id 用时间戳生成
        orderData.id = Date.now();
        orderData.status= 0; // 默认状态为待使用 0 待使用 1 已预约 2 待评价
        const order = new Order(orderData);
        await order.save();
        res.json({ code: 200, message: '订单添加成功', data: order });
    } catch (error) {
        res.status(500).json({ code: 500, message: '订单添加失败', error: error.message });
    }
});

// 查询订单（支持全部和按id查询）
router.get('/orders', async (req, res) => {
    try {
        const { id } = req.query;
        let orders;
        if (id) {
            orders = await Order.find({ id: Number(id) });
        } else {
            orders = await Order.find();
        }
        res.json({ code: 200, message: '查询订单成功', data: orders });
    } catch (error) {
        res.status(500).json({ code: 500, message: '查询订单失败', error: error.message });
    }
});

// 修改订单（根据id）
router.put('/orders', async (req, res) => {
    try {
        const { id } =req.body;
        const updateData = req.body;
        const order = await Order.findOneAndUpdate({ id: Number(id) }, updateData, { new: true });
        if (!order) {
            return res.status(404).json({ code: 404, message: '订单不存在' });
        }
        res.json({ code: 200, message: '订单修改成功', data: 'order' });
    } catch (error) {
        res.status(500).json({ code: 500, message: '订单修改失败', error: error.message });
    }
});



// 获取全部排班数据
router.get('/events', async (req, res) => {
    try {
        const schedules = await Schedule.find()
            .populate('technician', 'username sex age ')

        const events = schedules.map(schedule => ({
            id: schedule._id,
            title: schedule.title,
            start: schedule.start,
            end: schedule.end,
            allDay: schedule.allDay,
            color: schedule.color,
            technician: schedule.technician,
            status: schedule.status,
            notes: schedule.notes,
            createdBy: schedule.createdBy?.username || '未知用户',
            createTime: schedule.createTime
        }));
        res.json({
            success: true,
            data: events
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取排班数据失败',
            error: error.message
        });
    }
});

// 创建排班
router.post('/events', async (req, res) => {
    try {
        const { technician, title, start, end, notes,color} = req.body;
        // 验证必填字段
        if (!technician || !start || !end) {
            return res.status(400).json({
                success: false,
                message: '请提供完整的排班信息'
            });
        }

        // 检查时间冲突
        const conflict = await Schedule.checkConflict(technician, new Date(start), new Date(end));
        if (conflict) {
            return res.status(409).json({
                success: false,
                message: '该时间段已有排班'
            });
        }

        const schedule = new Schedule({
            technician: req.body.user.id,
            title: title || '工作安排',
            start: new Date(start),
            end: new Date(end),
            color: color || '#3788d8',
            notes: '客户备注:'+notes || '',
            createdBy: 'weixinyonghu'
        });

        await schedule.save();

        const populatedSchedule = await Schedule.findById(schedule._id)
            .populate('technician', 'username avatar skills')
            .populate('createdBy', 'username');

        res.json({
            success: true,
            data: populatedSchedule,
            message: '排班创建成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '创建排班失败',
            error: error.message
        });
    }
});

module.exports = router;